import React, { Component } from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Platform,
  ScrollView,
  Image,
  TouchableHighlight,
  TextInput,
  Alert,
  Linking
} from 'react-native'
import {Actions} from "react-native-router-flux";
import Icon from 'react-native-vector-icons/Ionicons'
import colors from './../../styles/colors'
import * as utils  from './../../utils/'
import RNAlibcSdk from 'react-native-alibc-sdk'
import * as WeChat from 'react-native-wechat'
import SplashScreen from 'react-native-splash-screen'
import { Overlay, Label, Button } from 'teaset'
import _updateConfig from '../../../update.json'
const {appKey} = _updateConfig[Platform.OS];

const PARAMS = {
  pid: "mm_108042659_0_0",
  forceH5: true
};

import {
  isFirstTime,
  isRolledBack,
  packageVersion,
  currentVersion,
  checkUpdate,
  downloadUpdate,
  switchVersion,
  switchVersionLater,
  markSuccess,
} from 'react-native-update';

class IndexScene extends Component{

  constructor(props){
    super(props)
    this.state = {
      priceItem: [5, 9, 15, 20],
      cateItem:[
        "冬季外套", "温暖上新", "套装", "卫衣",
        "上衣", "小白鞋", "连衣裙", "裙子",
        "美包", "短靴", "美妆", "男衣",
        "内衣袜子", "配件", "零食", "家具百货",
      ],
      cateItemImg: utils.indexCateImg,
      ready: false,
    }

    /* 初始化sdk(此方法为异步， 确保回调执行后再进行下一步操作)
     * 参数
     * pid: 绑定阿里妈妈帐号后在百川后台查询此帐号
     * forceH5：强制浏览器打开页面
     * callback: 回调函数
     */
    RNAlibcSdk.init(PARAMS.pid, PARAMS.forceH5, (err) => {
      if (!err)
        console.log("init success")
      else
        console.log(err)
      this.setState({ready: true});
    });
  }

  componentDidMount(){
    SplashScreen.hide();

    try {
      WeChat.registerApp('wx9773b34689e823ea');//从微信开放平台申请
    } catch (e) {
      console.error(e);
    }

    if (isFirstTime) {
      markSuccess()
    }

    //热更新
    this.checkUpdate();

  }


  doUpdate = info => {
    downloadUpdate(info).then(hash => {

      Overlay.show(this.renderUpdateView('下载完毕\n\n是否重启应用?', 'finish', hash))
    }).catch(err => {
      Alert.alert('提示', '更新失败');
    });
  };

  checkUpdate = () => {
    checkUpdate(appKey).then(info => {
      if (info.expired) {
        Overlay.show(this.renderUpdateView('版本已更新\n\n请前往应用商店下载新的版本', 'all', info))

      } else if (info.upToDate) {
        //Alert.alert('提示', '您的应用版本已是最新.');
      } else {


        Overlay.show(this.renderUpdateView('检查到新的版本\n'+info.name+',是否下载?\n\n'+ info.description, 'hot', info))
      }
    }).catch(err => {
      //Alert.alert('提示', '更新失败.');
    });
  };



  renderUpdateView(text, type, info){
    return(
      <Overlay.PopView
        style={{alignItems: 'center', justifyContent: 'center'}}
        ref={v => this.customPopView = v}
        onDisappearCompleted={()=>{
          if(type === 'finish'){
            console.log(123123)
            switchVersionLater(info)
          }
        }}
      >
        <View style={{backgroundColor: '#fff', minWidth: 230, minHeight: 180, borderRadius: 15, paddingVertical: 20, alignItems: 'center'}}>
          <Label type='title' size='lg' text='提示' />
          <View style={{marginHorizontal:15, alignItems:'center', marginVertical:20}}>
            <Label type='title' size='md' text={text} numberOfLines={10} style={{textAlign:'center'}}/>
          </View>
          <Button title='确定' onPress={() => {
            switch (type){
              case 'all':
                info.downloadUrl && Linking.openURL(info.downloadUrl)
                this.customPopView && this.customPopView.close()
                break;
              case 'hot':
                this.doUpdate(info);
                this.customPopView && this.customPopView.close()
                break;
              case 'finish':
                switchVersion(info)
                break;
            }


          }} style={{marginTop:10}} />
        </View>
      </Overlay.PopView>
    )
  }


  renderSearch(){ //搜索的布局样式
    return(
      <View style={styles.searchContainer}>
        <View style={styles.searchContent}>
          <Icon name="ios-search" size={24} style={styles.searchIcon}/>
          <TouchableOpacity style={{flex:1}} onPress={()=>{
            Actions.lists({searchModal:true})
          }}>
            <Text style={styles.searchText}>粘贴产品标题试试~</Text>
          </TouchableOpacity>
        </View>
      </View>
    )
  }

  renderPrice(){ //价格选择的布局样式
    return(
      <View style={styles.priceContainer}>
        <View style={styles.line}></View>
        <Text style={styles.lineText}>随便看看</Text>
        <View style={styles.priceItem}>
          {
            this.state.priceItem.map((e, i)=>{
              return(
                <TouchableOpacity style={styles.priceButton} key={i} onPress={()=>{
                  Actions.lists({sort:'price', endPrice:e})
                }}>
                  <Image style={styles.priceItemBg} source={require('./../../../assets/images/price_item_bg.png')}/>
                  <Text style={[{color:colors.white}, styles.priceItemText]}>{e}元专区</Text>
                </TouchableOpacity>
              )
            })
          }
        </View>
      </View>
    )
  }

  renderCategory(){ //分类选择的布局样式
    return(
      <View style={styles.cateContainer}>
        <View style={styles.line}></View>
        <Text style={styles.lineText}>热门市场</Text>
        <View style={styles.cateItem}>
          {
            this.state.cateItem.map((e, i)=>{
              let imaUrl = this.state.cateItemImg[i];
              return(
                <TouchableOpacity style={styles.cateBottom} key={i} onPress={()=>{
                  Actions.lists({sort:'sort', keyword: e})
                }}>
                  <Image source={imaUrl} style={styles.cateImg}/>
                  <Text style={{color:'#000'}}>{e}</Text>
                </TouchableOpacity>
              )
            })
          }
        </View>
      </View>
    )
  }

  render(){
    return(
      <View style={styles.container}>
        <View style={styles.logoContainer}>
          <Image style={styles.logo} source={require('./../../../assets/images/logo-nb.png')}/>
        </View>
          {this.renderSearch()}
        <ScrollView>
          {this.renderPrice()}
          {this.renderCategory()}
        </ScrollView>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container:{
    paddingTop: Platform.OS === 'ios' ? 20 : 0,
    backgroundColor:'#fff',
    flex:1,
    paddingHorizontal:10,
  },
  logoContainer:{
    justifyContent:'center',
    alignItems:'center',
    marginTop:30,
  },
  logo:{
    width:200,
    height:25
  },
  searchContainer:{
    marginTop:10,
    height:40,
    flexDirection:'row',
    marginBottom:10,
  },
  searchContent:{
    flex:1,
    backgroundColor:'#f6f6f6',
    // backgroundColor:'#f00',
    borderRadius:20,
    flexDirection:'row',
    alignItems:'center',
  },
  searchIcon:{
    marginLeft:10,
    color:colors.primary
  },
  searchText:{
    color:'#ccc',
    marginLeft:5,
    fontSize:12
  },
  priceContainer:{
    // backgroundColor:'#0f0',
    height:80,
  },
  line:{
    borderBottomColor:'#e8e8e8',
    borderBottomWidth:1.5,
    height:20,
  },
  lineText:{
    position:'absolute',
    top:10,
    backgroundColor:'#fff',
    left:140,
    color:'#000',
    fontSize:15
  },
  priceItem:{
    // backgroundColor:'#f00',
    marginTop:10,
    flex:1,
    justifyContent:'space-around',
    flexDirection:'row',
    alignItems:'center'
  },
  priceButton:{
    justifyContent:'center',
    alignItems:'center',
    width:70,
    height:30,
    position:'relative',
  },
  priceItemBg:{
    width:70,
    height:30,
  },
  priceItemText:{
    position:'absolute'
  },
  cateContainer:{
    // backgroundColor:'#f00',
  },
  cateItem:{
    flexDirection:'row',
    flexWrap:'wrap',
    justifyContent:'space-around',
    paddingVertical:10
  },
  cateBottom:{
    width:75,
    height:100,
    // backgroundColor:'#ff0',
    marginVertical:10,
    alignItems:'center'
  },
  cateImg:{
    width:75,
    height:80,
  }
})

export const LayoutComponent = IndexScene

export function mapStateToProps(state, props) {
    return {
        routes: state.routes,
    }
}